package com.bigtotoro.shuiyincamera.editimage;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.editimage.fragment.AddTextFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.AddWaterMarkFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.BaseEditFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.BeautyFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.CropFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.FilterListFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.FreePaintFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.ImageStickerFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.MainMenuFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.MountAddTextFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.MountImageStickerFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.MountWaterMarkFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.PaintFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.RemoveWaterMarkFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.RotateFragment;
import com.bigtotoro.shuiyincamera.editimage.fragment.StickerFragment;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.view.CropImageView;
import com.bigtotoro.shuiyincamera.editimage.view.CustomPaintView;
import com.bigtotoro.shuiyincamera.editimage.view.CustomViewPager;
import com.bigtotoro.shuiyincamera.editimage.view.RotateImageView;
import com.bigtotoro.shuiyincamera.editimage.view.StickerView;
import com.bigtotoro.shuiyincamera.editimage.view.TextStickerView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouch;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.editimage.widget.RedoUndoController;
import com.umeng.analytics.MobclickAgent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * <p>
 * 图片编辑 主页面
 *
 * @author panyi
 *         <p>
 *         包含 1.贴图 2.滤镜 3.剪裁 4.底图旋转 功能
 *         包含了顶部返回键、标题栏、保存按钮,底部的菜单
 *         底部的菜单是由mainMenuFragment
 */
public class EditImageActivity extends BaseActivity {
    public static final String FILE_PATH = "file_path";
    public static final String REAL_PATHS = "real_paths";
    public static final String MOUNT_FILE_PATH = "mount_file_path";
    public static final String MOUNT_OUTPUT_FILES = "mount_output_files";
    public static final String EXTRA_OUTPUT = "extra_output";
    public static final String PAGE_MODE = "page_mode";
    public static final String SAVE_FILE_PATH = "save_file_path";

    public static final String IMAGE_IS_EDIT = "image_is_edit";

    public static final int MODE_NONE = 0;  //以mode区分底部菜单现在是哪个菜单
    public static final int MODE_STICKERS = 1;// 贴图模式
    public static final int MODE_FILTER = 2;// 滤镜模式
    public static final int MODE_CROP = 3;// 剪裁模式
    public static final int MODE_ROTATE = 4;// 旋转模式
    public static final int MODE_TEXT = 5;// 文字模式
    public static final int MODE_PAINT = 6;//绘制模式
    public static final int MODE_BEAUTY = 7;//美颜模式
    public static final int MODE_REMOVE_WATERMARK = 8;// 去水印
    public static final int MODE_IMAGE_STICKERS = 9;// 添加图片水印
    public static final int MODE__REMOVE_WATER_MARK = 10;//去水印
    public static final int MODE__MOUNT_ADDTEXT = 11;//批量添加文本水印
    public static final int MODE__MOUNT_IMAGE_STICKER = 12;//批量添加图片水印

    public static String filePath;// 需要编辑图片路径
    public List<String> mountFilePaths;//批量图片路径
    public List<String> mount_output_files;//批量图片路径
    public String saveFilePath;// 生成的新图片路径
    public String pageMode;// 当前操作模式:图片裁剪，加水印，画板等
    private int imageWidth, imageHeight;// 展示图片控件 宽 高
    private LoadImageTask mLoadImageTask;

    public int mode = Constacts.MODE_NONE;// 当前操作模式

    protected int mOpTimes = 0;
    protected boolean isBeenSaved = false;

    private EditImageActivity mContext;
    private Bitmap mainBitmap;  //操作完成后获得的图片
    public ImageViewTouch mainImage; // 底部图层，放原始照片这一层
    private View backBtn;

    public ViewFlipper bannerFlipper;//应用按钮和保存按钮的父容器
    private View applyBtn;// 应用按钮
    private View saveBtn;// 保存按钮
    private TextView title;

    public StickerView mStickerView;// 贴图层View
    public CropImageView mCropPanel;// 剪切操作控件
    public CropImageView mRemoveWaterMarkPanel;// 剪切操作控件
    public RotateImageView mRotatePanel;// 旋转操作控件
    public TextStickerView mTextStickerView;//文本贴图显示View
    public CustomPaintView mPaintView;//涂鸦模式画板

    public CustomViewPager bottomGallery;// 底部横向滑动菜单
    private BottomGalleryAdapter mBottomGalleryAdapter;// 底部横向滑动菜单适配器
    private SaveImageTask mSaveImageTask;

    private MainMenuFragment mMainMenuFragment;// Menu
    private FreePaintFragment mFreePaintFragment;// Menu
    public StickerFragment mStickerFragment;// 贴图Fragment
    public FilterListFragment mFilterListFragment;// 滤镜FliterListFragment
    public RotateFragment mRotateFragment;// 图片旋转Fragment
    public BeautyFragment mBeautyFragment;//美颜模式Fragment

    public AddTextFragment mAddTextFragment;//图片添加文字
    public AddWaterMarkFragment mAddWaterMarkFragment;//图片添加水印（文字，自定义图片）
    public MountWaterMarkFragment mMountWaterMarkFragment;//批量加水印
    public CropFragment mCropFragment;// 图片剪裁Fragment
    public ImageStickerFragment mImageStickerFragment;// 图片剪裁Fragment
    public MountAddTextFragment mMountAddTextFragment;// 批量加文字水印fragment
    public MountImageStickerFragment mMountImageStickerFragment;// 批量加图片水印
    public RemoveWaterMarkFragment mRemoveWaterMarkFragment;// 图片剪裁Fragment
    public PaintFragment mPaintFragment;//绘制模式Fragment

    private RedoUndoController mRedoUndoController;//撤销操作

    /**
     * @param context
     * @param editImagePath
     * @param outputPath
     * @param requestCode
     */
    public static void start(Activity context, final String editImagePath, final String outputPath, final int requestCode, final String pageMode) {
        if (TextUtils.isEmpty(editImagePath)) {
            Toast.makeText(context, R.string.no_choose, Toast.LENGTH_SHORT).show();
            return;
        }

        Intent it = new Intent(context, EditImageActivity.class);
        it.putExtra(EditImageActivity.FILE_PATH, editImagePath);
        it.putExtra(EditImageActivity.EXTRA_OUTPUT, outputPath); //图片保存路径
        it.putExtra(EditImageActivity.PAGE_MODE, pageMode);
        context.startActivityForResult(it, requestCode);
    }

    public static void start2(Activity context, final List<String> imgPaths, final String editImagePath,
//                              final List<String> outputFiles,
                              final int requestCode, final String pageMode) {
        if (TextUtils.isEmpty(editImagePath)) {
            Toast.makeText(context, R.string.no_choose, Toast.LENGTH_SHORT).show();
            return;
        }

        Intent it = new Intent(context, EditImageActivity.class);
        it.putExtra(EditImageActivity.FILE_PATH, editImagePath);
        it.putExtra(EditImageActivity.MOUNT_FILE_PATH, (Serializable) imgPaths);//批量图片路径
//        it.putExtra(EditImageActivity.EXTRA_OUTPUT, outputPath);//图片保存路径
//        it.putExtra(EditImageActivity.MOUNT_OUTPUT_FILES, (Serializable) outputFiles);//图片保存路径
        it.putExtra(EditImageActivity.PAGE_MODE, pageMode);
        context.startActivityForResult(it, requestCode);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkInitImageLoader();//检测图片载入框架是否初始化
        setContentView(R.layout.activity_image_edit);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels / 2;
        imageHeight = metrics.heightPixels / 2;
        Log.d("onshow", "imageWidth====" + imageWidth + "imageHeight===" + imageHeight);
        getData();
        initView();
    }

    public List<Bitmap> bitmap_list = new ArrayList<>();
    public List<String> realPath_list = new ArrayList<>();

    private void getData() {
        filePath = getIntent().getStringExtra(FILE_PATH);
        mountFilePaths = (List<String>) getIntent().getSerializableExtra(MOUNT_FILE_PATH);
        mount_output_files = (List<String>) getIntent().getSerializableExtra(MOUNT_OUTPUT_FILES);
        saveFilePath = getIntent().getStringExtra(EXTRA_OUTPUT);// 保存图片路径
        pageMode = getIntent().getStringExtra(PAGE_MODE);

        if (mountFilePaths != null && mountFilePaths.size() > 0) {
            for (int i = 0; i < mountFilePaths.size(); i++) {
                String path = mountFilePaths.get(i);
                Bitmap bitmap = BitmapUtils.getSampledBitmap(path, imageWidth,
                        imageHeight);
                bitmap_list.add(bitmap);
                //载入图片地址后，生成了bitmap集合bitmap_list,供后续子fragment调用
            }
        }
        //从各个页面进入EditImageActivity中后，将获取到的图片载入
        loadImage(filePath);
    }

    private void initView() {  //在editImageActivity的initView方法中已经把各个fragment的实例创建出来了
        mContext = this;
//        DisplayMetrics metrics = getResources().getDisplayMetrics();
//        imageWidth = metrics.widthPixels / 2;
//        imageHeight = metrics.heightPixels / 2;

        title = findViewById(R.id.title);
        bannerFlipper = (ViewFlipper) findViewById(R.id.banner_flipper);//保存按钮和应用按钮的父容器，进行了封装
        bannerFlipper.setInAnimation(this, R.anim.in_bottom_to_top);
        bannerFlipper.setOutAnimation(this, R.anim.out_bottom_to_top);
        applyBtn = findViewById(R.id.apply);
        applyBtn.setOnClickListener(new ApplyBtnClick());
        saveBtn = findViewById(R.id.save_btn);
        saveBtn.setOnClickListener(new SaveBtnClick());

        mainImage = (ImageViewTouch) findViewById(R.id.main_image);// 页面正中的图片显示控件
        backBtn = findViewById(R.id.back_btn);// 左上角退出按钮
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        /**
         * 真正操作图片的画布，都只存放在editImageActivity中
         * */
        mStickerView = (StickerView) findViewById(R.id.sticker_panel); //添加图片表情的画布
        mCropPanel = (CropImageView) findViewById(R.id.crop_panel);//裁剪的画布
        mRemoveWaterMarkPanel = (CropImageView) findViewById(R.id.remove_water_mark_panel);//去水印的画布(自定义)
        mRotatePanel = (RotateImageView) findViewById(R.id.rotate_panel);//旋转画布
        mTextStickerView = (TextStickerView) findViewById(R.id.text_sticker_panel);//添加文字画布
        mPaintView = (CustomPaintView) findViewById(R.id.custom_paint_view);//涂鸦画布

        /**
         * 底部菜单容器，放置的是底部各种滤镜，剪裁等菜单和具体操作比如1:1,1:2等的菜单
         **/
        // 底部菜单容器，实际上是一个viewpager容器，放置的是MainMenuFragment，PaintFragment这些菜单fragment
        //这些fragment中存放的只有底部菜单，顶部返回按钮，保存应用按钮，撤回按钮等都只存在于editImageActivity中
        //
        bottomGallery = (CustomViewPager) findViewById(R.id.bottom_gallery);  //防止底部菜单的viewpager,其中放置的是各个分开功能的fragment
        //bottomGallery.setOffscreenPageLimit(7);
        mMainMenuFragment = MainMenuFragment.newInstance();//主菜单fragment
        mFreePaintFragment = FreePaintFragment.newInstance(EditImageActivity.this);
        mStickerFragment = StickerFragment.newInstance();//添加表情的fragment
        mFilterListFragment = FilterListFragment.newInstance();//滤镜fragment
        mCropFragment = CropFragment.newInstance();//裁剪fragment
        mImageStickerFragment = ImageStickerFragment.newInstance();//添加图片水印的fragment(自定义)
        mMountAddTextFragment = MountAddTextFragment.newInstance();
        mMountImageStickerFragment = MountImageStickerFragment.newInstance();
        mRemoveWaterMarkFragment = RemoveWaterMarkFragment.newInstance();//移除水印的fragment(自定义)
        mRotateFragment = RotateFragment.newInstance();//旋转fragment
        mAddTextFragment = AddTextFragment.newInstance();//添加文字fragment
        mAddWaterMarkFragment = mAddWaterMarkFragment.newInstance(EditImageActivity.this);//添加水印fragment(自定义)
        mMountWaterMarkFragment = mMountWaterMarkFragment.newInstance(EditImageActivity.this);//添加水印fragment(自定义)
        mPaintFragment = PaintFragment.newInstance(); //涂鸦fragment
        mBeautyFragment = BeautyFragment.newInstance(); //美颜fragment

        mBottomGalleryAdapter = new BottomGalleryAdapter(   //管理底部fragment的适配器
                this.getSupportFragmentManager());
        bottomGallery.setAdapter(mBottomGalleryAdapter);//底部菜单容器viewpager设置适配器


        mainImage.setFlingListener(new ImageViewTouch.OnImageFlingListener() {
            @Override
            public void onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                //System.out.println(e1.getAction() + " " + e2.getAction() + " " + velocityX + "  " + velocityY);
                if (velocityY > 1) {
                    closeInputMethod(); //关闭输入法。。。
                }
            }
        });
        //初始化撤销控件
        mRedoUndoController = new RedoUndoController(this, findViewById(R.id.redo_uodo_panel));
    }

    /**
     * 关闭输入法
     */
    private void closeInputMethod() {
        if (mAddTextFragment.isAdded()) {
            mAddTextFragment.hideInput();
        }
    }

    private BaseEditFragment mFragment;

    //所以BottomGalleryAdapter控制的是底部菜单栏显示哪些菜单
    //真正的裁剪画布，涂鸦画布等在editImageActivity中，只是控制显示隐藏
    private final class BottomGalleryAdapter extends FragmentPagerAdapter {
        public BottomGalleryAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int index) {   //选中不同的菜单按钮时，控制各个菜单的显示和隐藏
            //怎么控制的？他设置了一个展示fragment，选中谁，就设置mFragment等于谁，mFragment = mAddTextFragment;
            //单独菜单操作和多个菜单操作步骤不一样，多个菜单多了一个主菜单展示和点击按钮切换分菜单

            if (pageMode != null && !pageMode.equals("")) {
                switch (pageMode) {
                    case "加水印":
                        title.setText("图片加水印");
                        /*
                        * Can't change tag of fragment原因可能是有两个不同的指针指向了同一个fragment
                        * ***/
                        switch (index) {
                            case MainMenuFragment.INDEX:// 主菜单
                                return mAddWaterMarkFragment;
                            case StickerFragment.INDEX:// 贴图
                                return mStickerFragment;
                            case FilterListFragment.INDEX:// 滤镜
                                return mFilterListFragment;
                            case CropFragment.INDEX://剪裁
                                return mCropFragment;
                            case RotateFragment.INDEX://旋转
                                return mRotateFragment;
                            case AddTextFragment.INDEX://添加文字
                                return mAddTextFragment;
                            case PaintFragment.INDEX://绘制
                                return mPaintFragment;
                            case BeautyFragment.INDEX://美颜
                                return mBeautyFragment;
                            case ImageStickerFragment.INDEX://美颜
                                return mImageStickerFragment;

//                            case MainMenuFragment.INDEX: //添加水印主菜单
//                                return mAddWaterMarkFragment;
//                            case StickerFragment.INDEX: //添加表情水印
//                                return mStickerFragment;
//                            case FilterListFragment.INDEX: //添加文字水印
//                                return mAddTextFragment;
//                            case CropFragment.INDEX: //添加图片水印
//                                return mStickerFragment;
                        }
                        mFragment = mAddWaterMarkFragment;
                        break;
                    case "批量加水印":
                        title.setText("批量加水印");
                        /*
                        * Can't change tag of fragment原因可能是有两个不同的指针指向了同一个fragment
                        */
                        switch (index) {  //根据index的值来寻找fragment
                            case MainMenuFragment.INDEX:// 主菜单
                                return mMountWaterMarkFragment;
                            case StickerFragment.INDEX:// 贴图
                                return mStickerFragment;
                            case FilterListFragment.INDEX:// 滤镜
                                return mFilterListFragment;
                            case CropFragment.INDEX://剪裁
                                return mCropFragment;
                            case RotateFragment.INDEX://旋转
                                return mRotateFragment;
                            case AddTextFragment.INDEX://添加文字
                                return mAddTextFragment;
                            case PaintFragment.INDEX:
                                return mPaintFragment;//绘制
                            case BeautyFragment.INDEX://美颜
                                return mBeautyFragment;
                            case ImageStickerFragment.INDEX://美颜
                                return mImageStickerFragment;
                            case MountAddTextFragment.INDEX://美颜
                                return mMountAddTextFragment;
                            case MountImageStickerFragment.INDEX://美颜
                                return mMountImageStickerFragment;

                        }
                        mFragment = mMountWaterMarkFragment;
                        break;
                    case "去水印": //执行图片去水印操作
                        title.setText("图片去水印");
                        Log.i("去水印","执行了====mFragment.onShow");
                        mFragment = mRemoveWaterMarkFragment;
                        mFragment.onShow(EditImageActivity.this);

                        break;
                    case "图片裁剪":
                        title.setText("图片裁剪");
                        mFragment = mCropFragment;
                        mFragment.onShow(EditImageActivity.this); //单个页面就加这一句
                        break;
                    case "画板涂鸦":
                        title.setText("自由编辑");
                        switch (index) {   //点击子菜单出现空指针时，可能是count元素个数设置不对
                            case MainMenuFragment.INDEX:// 主菜单
                                return mMainMenuFragment;
                            case StickerFragment.INDEX:// 贴图
                                return mStickerFragment;
                            case FilterListFragment.INDEX:// 滤镜
                                return mFilterListFragment;
                            case CropFragment.INDEX://剪裁
                                return mCropFragment;
                            case RotateFragment.INDEX://旋转
                                return mRotateFragment;
                            case AddTextFragment.INDEX://添加文字
                                return mAddTextFragment;
                            case PaintFragment.INDEX:
                                return mPaintFragment;//绘制
                            case BeautyFragment.INDEX://美颜
                                return mBeautyFragment;
                        }
//                        mFragment.onShow(EditImageActivity.this);//单一功能时使用
                        mFragment = mMainMenuFragment;
                        break;
                }
            }
//            else {
//                switch (index) {
//                    case MainMenuFragment.INDEX:// 主菜单
//                        return mMainMenuFragment;
//                    case StickerFragment.INDEX:// 贴图
//                        return mStickerFragment;
//                    case FilterListFragment.INDEX:// 滤镜
//                        return mFilterListFragment;
//                    case CropFragment.INDEX://剪裁
//                        return mCropFragment;
//                    case RotateFragment.INDEX://旋转
//                        return mRotateFragment;
//                    case AddTextFragment.INDEX://添加文字
//                        return mAddTextFragment;
//                    case PaintFragment.INDEX:
//                        return mPaintFragment;//绘制
//                    case BeautyFragment.INDEX://美颜
//                        return mBeautyFragment;
//                }
//            }


//            mFragment.onShow(EditImageActivity.this); //调用的是各个菜单fragment中的onshow方法
            //原版是怎么执行的onshow方法呢？原版中是点击了主菜单上的各个分菜单按钮的时候，执行各个Fragment的onshow方法


//            activity.mode = EditImageActivity.MODE_TEXT;
//            activity.mainImage.setImageBitmap(activity.getMainBit());//设置界面正中的图片为
            //在setdata方法中，获取到从上一个Activity传递过来的图片路径
            //通过loadImage(filePath)启动异步载入图片,
//            activity.bannerFlipper.showNext();   //顶部保存按钮切换到应用按钮
//            mTextStickerView.setVisibility(View.VISIBLE); //添加文字画布切换为显示
//            mInputText.clearFocus();

//            mFragment.onShow();
            return mFragment;

//            switch (index) {
////                case MainMenuFragment.INDEX:// 主菜单
////                    return mMainMenuFragment;
////                case StickerFragment.INDEX:// 贴图
////                    return mStickerFragment;
////                case FilterListFragment.INDEX:// 滤镜
////                    return mFilterListFragment;
////                case CropFragment.INDEX://剪裁
////                    return mCropFragment;
////                case RotateFragment.INDEX://旋转
////                    return mRotateFragment;
////                case AddTextFragment.INDEX://添加文字
////                    return mAddTextFragment;
////                case PaintFragment.INDEX:
////                    return mPaintFragment;//绘制
////                case BeautyFragment.INDEX://美颜
////                    return mBeautyFragment;
//            }//end switch
//            return MainMenuFragment.newInstance();
        }

        //        @Override
//        public int getCount() {
//            return 1;
//        }
        public int getCount() {
            int count = 1;
            switch (pageMode) {
                case "加水印":
//                    count = 4;
                    count = 9;
                    break;
                case "批量加水印":
//                    count = 4;
//                    count = 9;
                    count = 11;
                    break;
                case "画板涂鸦":
                    count = 8;//希望全部功能可用时，用8
//                    count = 1;
                    break;
            }
            return count;
        }
    }

    /**
     * 异步载入编辑图片
     */
    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    /**
     * 导入文件图片任务
     * 为什么要搞一个异步载入图片，将图片转换成bitmap
     * 因为画布操作要用到bitmap?
     * 最后让mainbitmap == 生成的bitmap,各个子fragment可以直接调用
     * 这一步省不了。
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {  //设置显示在界面正中的图片的宽高，params[0]是图片路径
            Bitmap bitmap = BitmapUtils.getSampledBitmap(params[0], imageWidth,
                    imageHeight);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) { //参数是AsyncTask的第三个参数
            //将获得的bitmap存储起来
            //限定选中了多张图片时，存储bitmap
            //result为空。。。
//            if (mountFilePaths!=null && mountFilePaths.size()>0){
//                bitmap_list.add(result);
//            }

            changeMainBitmap(result, false);
//            changeMainBitmap(null, false);
        }
    }


    /**
     * 点击了back按钮，放弃保存状态并退出
     */
    @Override
    public void onBackPressed() {
        switch (mode) {
            case MODE_STICKERS:
                mStickerFragment.backToMain();
                return;
            case MODE_FILTER:// 滤镜编辑状态
                mFilterListFragment.backToMain();// 保存滤镜贴图
                return;
            case MODE_CROP:// 剪切图片保存
                mCropFragment.backToMain();
                return;
            case MODE_REMOVE_WATERMARK:// 去水印保存
                Log.i("去水印","执行了====onBackPressed MODE_REMOVE_WATERMARK ");
                mRemoveWaterMarkFragment.backToMain();
//                finish();
                return;
            case MODE_ROTATE:// 旋转图片保存
                mRotateFragment.backToMain();
                return;
            case MODE_TEXT:
                mAddTextFragment.backToMain();
                return;
            case MODE_PAINT:
                mPaintFragment.backToMain();
                return;
            case MODE_BEAUTY://从美颜模式中返回
                mBeautyFragment.backToMain();
                return;
            case MODE_IMAGE_STICKERS://从添加图片水印中返回
                mImageStickerFragment.backToMain();
                return;
            case MODE__MOUNT_ADDTEXT://从添加图片水印中返回
                mMountAddTextFragment.backToMain();
                return;
            case MODE__MOUNT_IMAGE_STICKER://从添加图片水印中返回
                mMountImageStickerFragment.backToMain();
                return;
        }// end switch

        if (canAutoExit()) {
            onSaveTaskDone();
        } else {//图片还未被保存    弹出提示框确认
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setMessage(R.string.exit_without_save)
                    .setCancelable(false).setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    setResult(RESULT_CANCELED);
                    mContext.finish();//图片还未保存是否退出，点确定直接退出
                }
            }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });

            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        }
    }

    /**
     * 应用按钮点击
     *
     * @author panyi
     */
    private final class ApplyBtnClick implements OnClickListener {
        @Override
        public void onClick(View v) {    //应用按钮点击为什么会弹出保存按钮？
            switch (mode) {
                case MODE_STICKERS:
                    mStickerFragment.applyStickers();// 保存贴图
                    break;
                case MODE_FILTER:// 滤镜编辑状态
                    mFilterListFragment.applyFilterImage();// 保存滤镜贴图
                    break;
                case MODE_ROTATE:// 旋转图片保存
                    mRotateFragment.applyRotateImage();
                    break;
                case MODE_TEXT://文字贴图 图片保存
                    mAddTextFragment.applyTextImage();
                    break;
                case MODE_PAINT://保存涂鸦
                    mPaintFragment.savePaintImage();
                    break;
                case MODE_BEAUTY://保存美颜后的图片
                    mBeautyFragment.applyBeauty();
                    break;
                case MODE_CROP:// 剪切图片保存
                    mCropFragment.applyCropImage();
                    break;
                case MODE_REMOVE_WATERMARK: // 去水印界面的应用按钮，点击后保存剪裁区域
                    Log.i("去水印","执行了====ApplyBtnClick 保存裁剪区域");
                    mRemoveWaterMarkFragment.applyCropImage();
                    break;
                case MODE_IMAGE_STICKERS: //添加图片水印
                    mImageStickerFragment.applyStickers();// 保存贴图
                    break;
                case MODE__MOUNT_ADDTEXT: //添加图片水印
                    mMountAddTextFragment.applyTextImage();// 保存贴图
                    break;
                case MODE__MOUNT_IMAGE_STICKER: //添加图片水印
                    mMountImageStickerFragment.applyStickers();// 保存贴图
                    break;
                default:
                    break;
            }// end switch
        }
    }// end inner class

    /**
     * 保存按钮 点击退出
     */
    private final class SaveBtnClick implements OnClickListener {
        @Override
        public void onClick(View v) {
            if (mOpTimes == 0) {//并未修改图片
                Log.i("去水印","执行了====SaveBtnClick  并未修改图片");
                mFragment = mRemoveWaterMarkFragment;
                ((RemoveWaterMarkFragment)mFragment).applyCropImage();//进行图片去水印操作
//                onSaveTaskDone();
            } else {
                Log.i("去水印","执行了====SaveBtnClick 保存修改图片 ");
                doSaveImage();
            }
        }
    }

//    private Handler handler=new Handler();

    //存储过程和生成bitmap集合的过程是分离的
    //这个方法做的是将bitmap集合中的bitmap存储进内存中
    //使用了FileOutputStream
    protected void doSaveImage() {
        if (mOpTimes <= 0)
            return;
        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }

        //在这里保存bitmap_list里的内容，取后一半的数据
            mSaveImageTask = new SaveImageTask();
            mSaveImageTask.execute(mainBitmap); //保存的是mainBitmap

    }

    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) { //第二个参数是是否将图片压栈
        if (newBit == null)  //如果获取到的图片为空，返回
            return;

        if (mainBitmap == null || mainBitmap != newBit) {  //如果获取到的图片为空，返回
            if (needPushUndoStack) {   //进入界面不执行，点击应用按钮执行
                mRedoUndoController.switchMainBit(mainBitmap, newBit);
                increaseOpTimes();
                //原来的流程是点击撤回会回到mainMenuFragment，然后再次点击裁剪才会出现裁剪页面
//                mFragment.onShowNoNextMenu(EditImageActivity.this);//重新创建一次菜单
                //如果改成onshow，点击应用之后不会弹出保存，还是弹出应用
//                mFragment.onShow(EditImageActivity.this);//重新创建一次菜单
            }
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }

        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }

        if (mRedoUndoController != null) {
            mRedoUndoController.onDestroy();
        }
    }

    public void increaseOpTimes() {
        mOpTimes++;
        isBeenSaved = false;
    }

    public void resetOpTimes() {
        isBeenSaved = true;
    }

    public boolean canAutoExit() {
        return isBeenSaved || mOpTimes == 0;
    }

    protected void onSaveTaskDone() {  //如果想退回到上一步就不能startActivityFroResult
        Intent returnIntent = new Intent();
        returnIntent.putExtra(FILE_PATH, filePath);
        returnIntent.putExtra(REAL_PATHS, (Serializable) realPath_list);
        returnIntent.putExtra(EXTRA_OUTPUT, saveFilePath);
        returnIntent.putExtra(IMAGE_IS_EDIT, mOpTimes > 0);

        FileUtil.ablumUpdate(this, saveFilePath,0);//更新相册
        setResult(RESULT_OK, returnIntent);
        finish();
    }

    /**
     * 保存图像，完成后退出、
     * 子fragment只是操作数据，真正的数据保存都放在EditImageActivity中
     * 超过3个就提示地址不存在
     */

    private final class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {
        private Dialog dialog;
        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))  //saveFilePath通过EditImageActivity.start方法中传入的
                return false;
            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }
        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            dialog.dismiss();
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = EditImageActivity.getLoadingDialog(mContext, R.string.saving_image, false);
            dialog.show();
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result) {
                resetOpTimes();
                onSaveTaskDone();
            } else {
                Toast.makeText(mContext, R.string.save_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public Bitmap getMainBit() {
        return mainBitmap;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageEnd("EditImageActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("EditImageActivity");//统计页面
        MobclickAgent.onPause(this);
    }


}